<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | create by allen.qiang
// +----------------------------------------------------------------------

/**
 * 用户操作类 permissionHandler
 * @package  htdocs
 * @subpackage  quanliadmin
 * create by allen.qiang
 * @version 1.0
 */

class userHandler {

    public function __construct( $dbca ) {
        $this->dbca = $dbca;
    }


    /**
     * 查询用户信息
     * @param array $arg_array 参数数组
     * $arg_array = array (
     *       'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchUserInfo( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //用户名
        if (isset($arg_array['userID']) && !empty($arg_array['userID'])) {
            $sql .= ' AND userID = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['userID'];
        }


        if ($sql) {
            $sql = 'WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 1) {

                //统计分类数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_master ' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                $arg_array['count'] = 0;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_master ' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
            if (!$temp_item_array) {
                return null;
            }

            foreach($temp_item_array as &$item) {

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'userID' => $item->userID,
                    'trueName' => $item->trueName,
                    'userPwd' => $item->userPwd,
                    'email' => $item->email,
                    'useFlg' => $item->useFlg,
                    'deliveryID' => $item->deliveryID,
                    'mobile' => $item->mobile,
                    'phone' => $item->phone,
                    'storeID' => $item->storeID,
                    'extend_1' => $item->extend_1,
                    'extend_2' => $item->extend_2,
                    'extend_3' => $item->extend_3,
                    'extend_4' => $item->extend_4,
                    'extend_5' => $item->extend_5,
                    'extend_6' => $item->extend_6,
                    'extend_7' => $item->extend_7,
                    'extend_8' => $item->extend_8
                );

            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;

        }

    }


    /**
     * 新增或修改权限
     * @param array $arg_array 权限参数数组
     * @return array
     */
    public function editPermission( $arg_array ){

        if (!isset($arg_array['uuid'], $arg_array['permissionID'], $arg_array['permissionName'], $arg_array['permissionGroupID'], $arg_array['permissionRequest'], $arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        //实例化公共类
        $commHandler = new commHandler();

        if (!$commHandler->isInteger( $arg_array['permissionID'], 1 )) {
            return array( 'code' => 400, 'message' => '请输入权限号' );
        }

        if (empty($arg_array['permissionName'])) {
            return array( 'code' => 400, 'message' => '请输入权限名称' );
        }

        if ($arg_array['permissionGroupID'] == 0) {
            return array( 'code' => 400, 'message' => '请选择权限组' );
        } else if ($arg_array['permissionGroupID'] == -1 && empty($arg_array['newGroup'])) {
            return array( 'code' => 400, 'message' => '请输入新权限组名称' );
        }

        if (empty($arg_array['permissionRequest'])) {
            return array( 'code' => 400, 'message' => '请输入权限路径' );
        }

        //获得权限数组
        $permission_group_array = $this->searchPermissionGroup();

        try {

            $permission_obj = new entity('user_permission');
            if (empty($arg_array['uuid'])) { //新增

                //查询权限ID是否已存在
                $p_arg_array = array(
                    'permissionID' => $arg_array['permissionID']
                );
                $permission_array = $this->searchPermission( $p_arg_array );
                if ($permission_array) {
                    throw new Exception('权限号已存在', 404);
                }

                //查询权限名称是否已存在
                $p_arg_array = array(
                    'permissionName' => $arg_array['permissionName']
                );
                $permission_array = $this->searchPermission( $p_arg_array );
                if ($permission_array) {
                    throw new Exception('权限名称已存在', 404);
                }

                //检查权限组
                if ($arg_array['permissionGroupID'] == -1) { //新建权限组

                    if ($permission_group_array) {
                        foreach($permission_group_array as &$group) {
                            if ($group['permissionGroupName'] == $arg_array['newGroup']) {
                                throw new Exception('权限组名称已存在', 404);
                            }
                            $permission_obj->permissionGroupID = $group['permissionGroupID'];
                        }
                        $permission_obj->permissionGroupID += 1;
                    } else {
                        $permission_obj->permissionGroupID = 1;
                    }
                    $permission_obj->permissionGroupName = $arg_array['newGroup'];

                } else { //已有权限组

                    $permission_obj->permissionGroupID = $arg_array['permissionGroupID'];
                    if (!isset($permission_group_array[$permission_obj->permissionGroupID])) {
                        throw new Exception('选择的权限组信息不存在', 404);
                    }
                    $permission_obj->permissionGroupName = $permission_group_array[$permission_obj->permissionGroupID]['permissionGroupName'];

                }

                unset($permission_group_array);

            } else { //修改

                //查询权限信息
                $permission_obj->uuid = $arg_array['uuid'];
                if (!$this->dbca->fetch($permission_obj)) {
                    throw new Exception('权限信息没有找到', 404);
                }

                if ($permission_obj->permissionID != $arg_array['permissionID']) {

                    //查询权限ID是否已存在
                    $p_arg_array = array(
                        'permissionID' => $arg_array['permissionID']
                    );
                    $permission_array = $this->searchPermission( $p_arg_array );
                    if ($permission_array) {
                        throw new Exception('权限号已存在', 404);
                    }

                }

                if ($permission_obj->permissionName != $arg_array['permissionName']) {

                    //查询权限名称是否已存在
                    $p_arg_array = array(
                        'permissionName' => $arg_array['permissionName']
                    );
                    $permission_array = $this->searchPermission( $p_arg_array );
                    if ($permission_array) {
                        throw new Exception('权限名称已存在', 404);
                    }

                }

                if ($arg_array['permissionGroupID'] != $permission_obj->permissionGroupID) {

                    //检查权限组
                    if ($arg_array['permissionGroupID'] == -1) { //新建权限组

                        if ($permission_group_array) {
                            foreach($permission_group_array as &$group) {
                                if ($group['permissionGroupName'] == $arg_array['newGroup']) {
                                    throw new Exception('权限组名称已存在', 404);
                                }
                                $permission_obj->permissionGroupID = $group['permissionGroupID'];
                            }
                            $permission_obj->permissionGroupID += 1;
                        } else {
                            $permission_obj->permissionGroupID = 1;
                        }
                        $permission_obj->permissionGroupName = $arg_array['newGroup'];

                    } else { //已有权限组

                        $permission_obj->permissionGroupID = $arg_array['permissionGroupID'];
                        if (!isset($permission_group_array[$permission_obj->permissionGroupID])) {
                            throw new Exception('选择的权限组信息不存在', 404);
                        }
                        $permission_obj->permissionGroupName = $permission_group_array[$permission_obj->permissionGroupID]['permissionGroupName'];

                    }

                    unset($permission_group_array);

                }


            }
            $permission_obj->permissionID = $arg_array['permissionID'];
            $permission_obj->permissionName = $arg_array['permissionName'];
            $permission_obj->permissionRequest = $arg_array['permissionRequest'];
            $this->dbca->save( $permission_obj );

            return array( 'code' => 200, 'message' => '权限保存成功' );

        } catch( Exception $e ) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询权限信息
     * @param $arg_array
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return array|null
     */
    public function searchPermission( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //权限ID
        if (isset($arg_array['permissionID']) && is_numeric($arg_array['permissionID'])) {
            $sql .= ' AND permissionID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['permissionID'];
        }

        //权限名称
        if (isset($arg_array['permissionName']) && !empty($arg_array['permissionName'])) {
            $sql .= ' AND permissionName = ?';
            $params_type .= 's';
            $params_array[] = $arg_array['permissionName'];
        }

        //权限组ID
        if (isset($arg_array['permissionGroupID']) && is_numeric($arg_array['permissionGroupID'])) {
            $sql .= ' AND permissionGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['permissionGroupID'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_permission' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_permission' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if (!$temp_item_array) {
                return null;
            }

            foreach ($temp_item_array as &$item) {

                $item_array[] = array(
                    'uuid' => $item->uuid,
                    'permissionID' => $item->permissionID,
                    'permissionName' => $item->permissionName,
                    'permissionRequest' => $item->permissionRequest,
                    'permissionGroupID' => $item->permissionGroupID,
                    'permissionGroupName' => $item->permissionGroupName
                );
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 查询权限组信息
     * @return mixed
     */
    public function searchPermissionGroup() {

    	$sql = 'SELECT permissionGroupID,permissionGroupName FROM user_permission GROUP BY permissionGroupID ORDER BY permissionGroupID ASC';

    	$temp_item_array = $this->dbca->stmt_query($sql);

        if (!$temp_item_array) {
            return null;
        }

        foreach($temp_item_array as &$item) {
            $item_array[$item->permissionGroupID] = array(
                'permissionGroupID' => $item->permissionGroupID,
                'permissionGroupName' => $item->permissionGroupName
            );
        }

    	return $item_array;

    }

    /**
     * 删除权限
     * @param array $permission_array 权限ID数组
     * @return array
     */
    public function deletePermission( $permission_array ) {

        if (!isset($permission_array) || !is_array($permission_array) || empty($permission_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

    	try {

            foreach ($permission_array as &$permissionID) {

                if (!is_numeric($permissionID) || $permissionID <= 0) {
                    continue;
                }

                $delete_sql = 'DELETE FROM user_permission WHERE permissionID = ?';
                $this->dbca->stmt_query($delete_sql, 'i', $permissionID);

            }

    		return array( 'code' => 200, 'message' => '权限删除成功' );
    
    	} catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

    	}
    
    }



    /**
     * 查询角色组信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchRoleGroup( &$arg_array ){

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //角色组ID
        if (isset($arg_array['roleGroupID']) && is_numeric($arg_array['roleGroupID'])) {
            $sql .= ' AND roleGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleGroupID'];
        }

        //角色组名
        if (isset($arg_array['roleGroupName']) && !empty($arg_array['roleGroupName'])) {
            $sql .= ' AND roleGroupName = ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['roleGroupName'] . '%';
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_rolegroup' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_rolegroup' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'uuid' => $item->uuid,
                        'roleGroupID' => $item->roleGroupID,
                        'roleGroupName' => $item->roleGroupName,
                        'memo' => $item->memo
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 新增或修改角色组
     * @param array $arg_array 角色组参数信息
     * @return array
     */
    public function editRoleGroup( $arg_array ) {

        if (!isset($arg_array['roleGroupID'], $arg_array['roleGroupName'], $arg_array['operator'], $arg_array['memo'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['roleGroupID'])) {
            $arg_array['roleGroupID'] = 0;
        }

        if (empty($arg_array['roleGroupName'])) {
            return array( 'code' => 400, 'message' => '请输入角色组名称' );
        }

        try {

            $this->dbca->beginTransaction();

            $role_group_obj = new entity('user_rolegroup');
            if ($arg_array['roleGroupID'] > 0) {
                $role_group_obj->roleGroupID = $arg_array['roleGroupID'];
                if (!$this->dbca->fetch($role_group_obj)) {
                    throw new Exception('角色组信息没有找到', 404);
                }

                //更新角色表中角色组名称
                $update_sql = 'UPDATE user_role SET roleGroupName = ? WHERE roleGroupID = ?';
                $this->dbca->stmt_query($update_sql, 'si', convertVar($arg_array['roleGroupName']), $arg_array['roleGroupID']);

            } else {
                $role_group_obj->creator = $arg_array['operator'];
            }
            $role_group_obj->roleGroupName = convertVar($arg_array['roleGroupName']);
            $role_group_obj->memo = convertVar($arg_array['memo']);
            $this->dbca->save($role_group_obj);

            $this->dbca->commit();

            if ($arg_array['roleGroupID'] > 0) {
                return array( 'code' => 200, 'message' => '角色组修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '角色组新增成功' );
            }

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询角色信息
     * @param array $arg_array                          查询参数数组
     * $arg_array = array (
     *      'sortname' => string 排序字段
     *       'sortorder' => string 排序方式
     *       'page' => int 分页页码
     *       'rp' => int 分页页数
     * )
     * @return null|array
     */
    public function searchRole ( &$arg_array ) {

        //sql字符串
        $sql = '';

        //参数类型字符串
        $params_type = '';

        //参数值数组
        $params_array = array();

        //角色ID
        if (isset($arg_array['roleID']) && is_numeric($arg_array['roleID'])) {
            $sql .= ' AND roleID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleID'];
        }

        //角色名
        if (isset($arg_array['roleName']) && !empty($arg_array['roleName'])) {
            $sql .= ' AND roleName = ?';
            $params_type .= 's';
            $params_array[] = '%' . $arg_array['roleName'] . '%';
        }

        //角色组ID
        if (isset($arg_array['roleGroupID']) && is_numeric($arg_array['roleGroupID'])) {
            $sql .= ' AND roleGroupID = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['roleGroupID'];
        }

        //使用标志
        if (isset($arg_array['useFlg']) && is_array($arg_array['useFlg'], array(0, 1))) {
            $sql .= ' AND useFlg = ?';
            $params_type .= 'i';
            $params_array[] = $arg_array['useFlg'];
        }

        if ($sql) {
            $sql = ' WHERE ' . substr($sql, 4);
        }

        try {

            if (isset($arg_array['rp']) && $arg_array['rp'] > 0) {

                //统计数量
                $search_sql = 'SELECT COUNT(*) AS item_count FROM user_role' . $sql;
                $count_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);
                $item_count = $count_array[0]->item_count;
                if ($item_count == 0) {
                    $arg_array['count'] = 0;
                    return null;
                }

                $arg_array['count'] = $item_count;

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

                //分页
                if (!isset($arg_array['page']) || !is_numeric($arg_array['page']) || $arg_array['page'] <= 0)
                    $arg_array['page'] = 1;

                $sql .= sprintf(' LIMIT %d, %d', ($arg_array['page'] - 1) * $arg_array['rp'], $arg_array['rp']);

            } else {

                //排序
                if (isset($arg_array['sortname']) && !empty($arg_array['sortname']))
                    $sql .= sprintf(' ORDER BY %s %s', $arg_array['sortname'], $arg_array['sortorder']);

            }

            //查询分类信息
            $search_sql = 'SELECT * FROM user_role' . $sql;
            $temp_item_array = &$this->dbca->stmt_query($search_sql, $params_type, $params_array);

            if ($temp_item_array) {
                foreach ($temp_item_array as &$item) {

                    $item_array[] = array(
                        'uuid' => $item->uuid,
                        'roleID' => $item->roleID,
                        'roleName' => $item->roleName,
                        'roleGroupID' => $item->roleGroupID,
                        'roleGroupName' => $item->roleGroupName,
                        'useFlg' => $item->useFlg,
                        'memo' => $item->memo
                    );
                }
            }

            return $item_array;

        } catch (Exception $e) {

            error_log($e->getMessage());
            return null;
        }

    }

    /**
     * 新增/修改角色
     * @param array $arg_array 角色参数数组
     * @return array
     */
    public function editRole( $arg_array ) {

        if (!isset($arg_array['roleGroupID'], $arg_array['roleID'], $arg_array['operator'], $arg_array['memo'], $arg_array['roleName'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }
        if (!is_numeric($arg_array['roleID'])) {
            $arg_array['roleID'] = 0;
        }

        if ($arg_array['roleGroupID'] <= 0) {
            return array( 'code' => 400, 'message' => '请选择角色组' );
        }

        if (empty($arg_array['roleName'])) {
            return array( 'code' => 400, 'message' => '角色名称不能为空' );
        }

        try {

            //查询角色组信息
            $t_arg_array = array(
                'roleGroupID' => $arg_array['roleGroupID']
            );
            $role_group_array = $this->searchRoleGroup( $t_arg_array );
            if (!$role_group_array) {
                throw new Exception('角色组信息没有找到', 404);
            }

            $role_obj = new entity('user_role');
            if ($arg_array['roleID'] > 0) {
                $role_obj->roleID = $arg_array['roleID'];
                if (!$this->dbca->fetch($role_obj)) {
                    throw new Exception('角色信息没有找到', 404);
                }
            } else {
                $role_obj->creator = $arg_array['operator'];
            }
            $role_obj->roleName = convertVar($arg_array['roleName']);
            $role_obj->roleGroupID = $role_group_array[0]['roleGroupID'];
            $role_obj->roleGroupName = $role_group_array[0]['roleGroupName'];
            $role_obj->useFlg = 1;
            $role_obj->memo = convertVar($arg_array['memo']);
            $this->dbca->save($role_obj);

            if ($arg_array['roleID'] > 0) {
                return array( 'code' => 200, 'message' => '角色修改成功' );
            } else {
                return array( 'code' => 200, 'message' => '角色新增成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 查询角色权限信息
     * @param int $importData
     * @return array
     */
    public function searchRolePermission( $roleID ){

        $search_sql = 'SELECT * FROM user_rolepermission WHERE roleID = ?';
        $permission_array = &$this->dbca->stmt_query($search_sql, 'i', $roleID);

        if (!$permission_array) {
            return null;
        }

        foreach($permission_array as &$permission) {
            $item_array[$permission->permissionID] = 1;
        }

        return $item_array;

    }

    /**
     * 添加角色权限
     * @param $importData
     * @return array
     */
    public function editRolePermission( $arg_array ) {

        if (!isset($arg_array['operator'], $arg_array['checkPer'], $arg_array['roleID']) || empty($arg_array['operator'])
            || !is_array($arg_array['checkPer']) || !is_numeric($arg_array['roleID'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (empty($arg_array['checkPer'])) {
            return array( 'code' => 400, 'message' => '请选择权限' );
        }

        try {

            $this->dbca->beginTransaction();

            //查询角色信息
            $r_arg_array = array(
                'roleID' => $arg_array['roleID']
            );
            $role_array = $this->searchRole( $r_arg_array );
            if (!$role_array) {
                throw new Exception('角色信息没有找到', 404);
            }

            //删除已有的角色权限
            $delete_sql = 'DELETE FROM user_rolepermission WHERE roleID = ' . $arg_array['roleID'];
            $this->dbca->stmt_query($delete_sql);

            //保存新的权限

            $insert_sql = 'INSERT INTO user_rolepermission (uuid,timeStamp,creator,createTime,roleID,permissionGroupID,permissionID) VALUES ';
            $insert_num = 0;
            $datetime = date(G_DEFAULT_DATETIME_FORMAT);

            foreach($arg_array['checkPer'] as &$permissionID) {

                //查询权限信息
                $p_arg_array = array(
                    'permissionID' => $permissionID
                );
                $permission_array = $this->searchPermission( $p_arg_array );
                if (!$permission_array) {
                    continue;
                }

                if ($insert_num > 0) {
                    $insert_sql .= ',';
                }
                $insert_sql .= sprintf('("%s", "%s", "%s", "%s", %s, %s, %s)', make_uuid(), $datetime, $arg_array['operator'], $datetime,
                    $arg_array['roleID'], $permission_array[0]['permissionGroupID'], $permission_array[0]['permissionID']);

                ++$insert_num;

            }

            if ($insert_num == 0) {
                throw new Exception('请选择权限', 400);
            }
			
            $this->dbca->stmt_query($insert_sql);

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => '角色权限保存成功' );

    }


    /**
     * 新增或修改用户信息
     * @param array $arg_array 用户数组
     * @return array
     */
    public function editUser ( $arg_array ) {

        //实例化公共类
        $commHandler = new commHandler();

        if (!isset($arg_array['operator'], $arg_array['userID'], $arg_array['trueName'], $arg_array['userPwd'], $arg_array['repeatPwd'],
            $arg_array['email'], $arg_array['user_role'], $arg_array['uuid']) || empty($arg_array['operator'])) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        if (empty($arg_array['userID'])) {
            return array( 'code' => 400, 'message' => '用户名不能为空' );
        }

        if (empty($arg_array['trueName'])) {
            return array( 'code' => 400, 'message' => '用户姓名不能为空' );
        }

        if (empty($arg_array['uuid']) || (!empty($arg_array['uuid']) && !empty($arg_array['userPwd']))) {

            if (!$commHandler->isPwd($arg_array['userPwd'])) {
                return array( 'code' => 400, 'message' => '密码必须是6-30位字符，可使用字母、数字或符号的组合' );
            }
            if ($arg_array['userPwd'] != $arg_array['repeatPwd']) {
                return array( 'code' => 400, 'message' => '两次输入的密码不一致' );
            }

        }

        if (!$commHandler->isEmail($arg_array['email'])) {
            return array( 'code' => 400, 'message' => '邮件不能为空或格式错误' );
        }

        if (empty($arg_array['user_role'])) {
            return array( 'code' => 400, 'message' => '请选择用户角色' );
        }

        if (!isset($arg_array['useFlg']) || !in_array($arg_array['useFlg'], array(0, 1))) {
            $arg_array['useFlg'] = 1;
        }

        try {

            $this->dbca->beginTransaction();

            if (isset($arg_array['mallID']) && $arg_array['mallID'] > 0) {

                //加载门店类
                quanli_include('module/base/mallHandler.class.php');

                //实例门店类
                $mallHandler = new mallHandler( $this->dbca );

                //查询门店信息
                $b_arg_array = array(
                    'mallID' => $arg_array['mallID'],
                    'useFlg' => 1
                );
                $mall_array = $mallHandler->searchMall( $b_arg_array );
                if (!$mall_array) {
                    throw new Exception('门店信息没有找到', 404);
                }

            }

            //检查并保存用户信息
            $user_obj = new entity('user_master');
            $user_obj->userID = $arg_array['userID'];
            if ($this->dbca->fetch($user_obj)) {

                if ($user_obj->uuid != $arg_array['uuid']) {
                    throw new Exception('用户已存在，请使用其他用户名', 404);
                }

            } else {

                if (!empty($arg_array['uuid'])) {
                    throw new Exception('用户信息没有找到', 404);
                }
                $user_obj->creator = $arg_array['operator'];

            }
            $user_obj->trueName = $commHandler->convertVar($arg_array['trueName']);
            if (!empty($arg_array['userPwd']))
                $user_obj->userPwd = md5($arg_array['userPwd']);
            $user_obj->trueName = $commHandler->convertVar($arg_array['trueName']);
            $user_obj->email = $commHandler->convertVar($arg_array['email']);
            if (isset($mall_array)) {
                $user_obj->extend_1 = $mall_array[0]['mallID'];
                $user_obj->extend_3 = $mall_array[0]['mallName'];
            } else {
                $user_obj->extend_1 = null;
                $user_obj->extend_3 = null;
            }
            if (isset($arg_array['store']) && !empty($arg_array['store']) && is_array($arg_array['store'])) {
                $user_obj->storeID = implode(',', $arg_array['store']);
            }
            $user_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save( $user_obj );

            //删除用户角色信息
            $del_sql = 'DELETE FROM user_userrole WHERE userID = ?';
            $this->dbca->stmt_query($del_sql, 's', $arg_array['userID']);

            //保存用户的角色信息
            $role_num = 0;

            foreach($arg_array['user_role'] as &$role_id) {

                //查询角色信息
                $r_arg_array = array(
                    'roleID' => $role_id
                );
                $role_array = $this->searchRole( $r_arg_array );
                if (!$role_array) {
                    continue;
                }

                $role_obj = new entity('user_userrole');
                $role_obj->creator = $arg_array['operator'];
                $role_obj->userID = $arg_array['userID'];
                $role_obj->roleID = $role_id;
                if ($this->dbca->save($role_obj)) {
                    ++$role_num;
                }

            }

            if ($role_num == 0) {
                throw new Exception('用户角色保存失败', 404);
            }

            $this->dbca->commit();

        } catch (Exception $e) {

            $this->dbca->rollBack();

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => '用户信息保存成功' );
    	
    }

    /**
     * 查询用户的角色信息
     * @param string $userID 用户名
     * @return null
     */
    public function searchUserRole( $userID ) {

        if (!isset($userID) || empty($userID)) {
            return null;
        }

        $search_sql = 'SELECT * FROM user_userrole WHERE userID = ?';
        $user_role_array = &$this->dbca->stmt_query($search_sql, 's', $userID);
        if (!$user_role_array) {
            return null;
        }

        foreach($user_role_array as &$role) {
            $item_array[$role->roleID] = $role->roleID;
        }

        return $item_array;

    }

    /**
     * 启用或禁用用户
     * @param array $arg_array
     * @return array
     */
    public function changeUserUse ( $arg_array ) {

        if (!isset($arg_array['userID'], $arg_array['useFlg']) || empty($arg_array['userID']) || !in_array($arg_array['useFlg'], array(0, 1))) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            //查询用户信息
            $user_obj = new entity('user_master');
            $user_obj->userID = $arg_array['userID'];
            if (!$this->dbca->fetch($user_obj)) {
                throw new Exception('用户信息没有找到', 404);
            }

            if ($user_obj->useFlg == 1 && $arg_array['useFlg'] == 1) {
                throw new Exception('用户已启用', 404);
            }

            if ($user_obj->useFlg == 0 && $arg_array['useFlg'] == 0) {
                throw new Exception('用户已禁用', 404);
            }
            $user_obj->useFlg = $arg_array['useFlg'];
            $this->dbca->save($user_obj);

            if ($arg_array['useFlg'] == 1) {
                return array( 'code' => 200, 'message' => '用户启用成功' );
            } else {
                return array( 'code' => 200, 'message' => '用户禁用成功' );
            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 批量删除用户
     * @param array $user_array 用户名数组
     */
    public function deleteUser( $user_array ) {

        if (!isset($user_array) || !is_array($user_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            if (!empty($user_array)) {

                foreach($user_array as &$userID) {

                    //查询用户信息
                    $user_obj = new entity('user_master');
                    $user_obj->userID = $userID;
                    if (!$this->dbca->fetch($user_obj)) {
                        continue;
                    }
                    $this->dbca->delete($user_obj);

                }

            }

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

        return array( 'code' => 200, 'message' => '用户删除成功' );

    }
    
    /**
     * 批量删除角色信息
     * @param array $arg_array 角色组参数数组
     * @return array
     * @throws Exception
     */
    public function deleteRole ( $arg_array ) {

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400, 'message' => '请选择要删除的角色' );
        }

        try {

            foreach($arg_array as &$roleID) {

                //检查角色信息
                $role_obj = new entity('user_role');
                $role_obj->roleID = $roleID;
                if (!$this->dbca->fetch($role_obj)) {
                    continue;
                }
                $this->dbca->delete( $role_obj );

            }

            return array( 'code' => 200, 'message' => '角色删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 批量删除角色组信息
     * @param array $arg_array 角色组参数数组
     * @return array
     * @throws Exception
     */
    public function deleteRoleGroup( $arg_array ) {

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400, 'message' => '请选择要删除的角色组' );
        }

        try {

            foreach($arg_array as &$roleGroupID) {

                //检查角色组信息
                $role_group_obj = new entity('user_rolegroup');
                $role_group_obj->roleGroupID = $roleGroupID;
                if (!$this->dbca->fetch($role_group_obj)) {
                    continue;
                }
                $this->dbca->delete( $role_group_obj );

            }

            return array( 'code' => 200, 'message' => '角色组删除成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }

    /**
     * 添加用户短信消息黑名单
     * @param array $arg_array 角色mobile
     * @return array
     * @throws Exception
     */
    public function creatBlackUser($arg_array){

        if (!isset($arg_array) || !is_array($arg_array) || empty($arg_array)) {
            return array( 'code' => 400, 'message' => '参数错误' );
        }

        try {

            foreach($arg_array as $mobile) {

                //检查会员信息
                $cust_master_obj = new entity('cust_master');
                $cust_master_obj->mobile = $mobile;

                if (!$this->dbca->fetch($cust_master_obj)) {
                    //检查会员信息
                    $cust_latent_pool_obj = new entity('cust_latent_pool');
                    $cust_latent_pool_obj->mobile = $mobile;
                    if (!$this->dbca->fetch($cust_latent_pool_obj)) {
                        continue;
                    }
                    $sql = ' SELECT latentSeqno FROM `cust_latent_pool` WHERE mobile = ? ';
                    $cust_latent_pool = $this->dbca->stmt_query($sql,'s',array($mobile));
                }else{
                    $sql = ' SELECT pcustID FROM `cust_master` WHERE mobile = ? ';
                    $cust_master = $this->dbca->stmt_query($sql,'s',array($mobile));
                }

                //存储黑名单
                $cust_blacklist = new entity('cust_blacklist');
                if($cust_latent_pool){
                    $cust_blacklist->latentSeqno = $cust_latent_pool[0]->latentSeqno;
                }
                if($cust_master){
                    $cust_blacklist->pcustID = $cust_master[0]->pcustID;
                }

                $cust_blacklist->messageBFlg = 1;
                $cust_blacklist->blackReason = '客户退订';
                $this->dbca->save( $cust_blacklist );
            }

            return array( 'code' => 200, 'message' => '短信退订成功' );

        } catch (Exception $e) {

            if ($e->getCode() > 0) {
                return array( 'code' => $e->getCode(), 'message' => $e->getMessage() );
            } else {
                error_log($e->getMessage());
                return array( 'code' => 500, 'message' => '系统错误' );
            }

        }

    }
}